﻿Imports NVelocity
Imports NVelocity.App
Imports NVelocity.Context

Imports System.Collections.Generic
Imports System.IO

Imports System.Data
Imports System.Data.SqlClient

Partial Class WebForm_ManageWorkRecord_AddDirtyHeader
    Inherits My.MyUserControl
    Dim wrManager As New WorkRecordManager
    Protected Overrides Sub OnInit(ByVal e As EventArgs)
        MyBase.OnInit(e)
        Me.Controls.Add(Me.LoadControl("~/WebForm/CommonControl/GoogleMapExif.ascx"))
    End Sub

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
     
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ScriptManager.GetCurrent(Page).RegisterPostBackControl(Me.btnExport)
        ScriptManager.GetCurrent(Page).RegisterPostBackControl(Me.btnSave)
        ScriptManager.GetCurrent(Page).RegisterPostBackControl(Me.btnApprove)
        ScriptManager.GetCurrent(Page).RegisterPostBackControl(Me.btnUploadFile)
        btnSave.Attributes("onclick") = "this.disabled=true;" & Me.Page.ClientScript.GetPostBackEventReference(btnSave, "")
        btnApprove.Attributes.Add("onclick", "this.disabled=true; if(confirm('確定審核?')){" & Page.ClientScript.GetPostBackEventReference(btnApprove, "").ToString() & "} else{this.disabled = false;return false;}")

    End Sub

    '開窗取值-PlanName
    Protected Sub btnSearchDirtyHeader_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearchDirtyHeader.Click
        SearchDirtyHeaderControl1.InitDataAndShow()
    End Sub

    '開窗取值回來-PlanName
    Protected Sub SearchDirtyHeaderControl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles SearchDirtyHeaderControl1.SelectedIndexChanged
        txtDirtyHeaderName.Text = SearchDirtyHeaderControl1.SelectedText
        FindDirtyHeaderID = SearchDirtyHeaderControl1.SelectedValue

        Me.BindDirtyHeader()

    End Sub

    '開窗取值-Volunteer
    Protected Sub btnShowPerson_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnShowPerson.Click

        Dim sql As New MyStringBuilder
        Dim dat As New clsData


        Using scope As New Transactions.TransactionScope
            If DataAccessMode = FormDataAccessMode.Take And Me.WorkHeaderID = 0 Then

                sql.Length = 0
                sql.AppendFormat("Insert Into WorkHeader(CreateDate,CreateBy) ")
                sql.AppendFormat("SELECT getdate(),'{0}' ", Me.Page.User.Identity.Name)
                dat.AccData(sql)
                WorkHeaderID = MyObj.GetIdentity()

            End If
            scope.Complete()
        End Using
        SearchVolunteerControl_AddDirtyHeader1.WorkHeaderID = WorkHeaderID
        SearchVolunteerControl_AddDirtyHeader1.InitDataAndShow()
    End Sub

    '開窗取值回來-Volunteer
    Protected Sub SearchVolunteerControl1_OK_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SearchVolunteerControl_AddDirtyHeader1.OK_Click

        Me.SavePerson()
        Me.BindGV()
    End Sub
    Protected Sub GridView_Volunteers_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView_VolunteersDirty.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim chkSignIn As CheckBox = TryCast(e.Row.FindControl("chkSignIn"), CheckBox)
            Dim chkSignOut As CheckBox = TryCast(e.Row.FindControl("chkSignOut"), CheckBox)

            Dim CheckStatus As Integer = DataBinder.Eval(e.Row.DataItem, "Status").ToString()

            If CheckStatus = 1 Then
                chkSignIn.Checked = True
                chkSignOut.Checked = False
            ElseIf CheckStatus = 2 Then
                chkSignIn.Checked = False
                chkSignOut.Checked = True
            ElseIf CheckStatus = 3 Then
                chkSignIn.Checked = True
                chkSignOut.Checked = True
            Else
                chkSignIn.Checked = False
                chkSignOut.Checked = False
            End If

            Dim chkAllSignIn As CheckBox = TryCast(Me.GridView_VolunteersDirty.HeaderRow.FindControl("chkAllSignIn"), CheckBox)
            Dim chkAllSignOut As CheckBox = TryCast(Me.GridView_VolunteersDirty.HeaderRow.FindControl("chkAllSignOut"), CheckBox)

            chkAllSignIn.Checked = chkAllSignIn.Checked And chkSignIn.Checked
            chkAllSignOut.Checked = chkAllSignOut.Checked And chkSignOut.Checked
        End If
    End Sub

    Protected Sub GridView_Volunteers_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView_VolunteersDirty.DataBound
        If Me.DataAccessMode = FormDataAccessMode.Take Then
            '隱藏時數
            '隱藏簽到狀態
            Me.GridView_VolunteersDirty.Columns(3).Visible = False
            '  Me.GridView_VolunteersDirty.Columns(5).Visible = False
            Me.GridView_VolunteersDirty.Columns(Me.GridView_VolunteersDirty.Columns.Count - 2).Visible = False
            Me.GridView_VolunteersDirty.Columns(Me.GridView_VolunteersDirty.Columns.Count - 3).Visible = False
        Else
            Me.GridView_VolunteersDirty.Columns(3).Visible = True
            ' Me.GridView_VolunteersDirty.Columns(5).Visible = True
            Me.GridView_VolunteersDirty.Columns(Me.GridView_VolunteersDirty.Columns.Count - 2).Visible = True
            Me.GridView_VolunteersDirty.Columns(Me.GridView_VolunteersDirty.Columns.Count - 3).Visible = True
        End If

    End Sub
    Protected Sub btnUploadFile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUploadFile.Click
        Me.UploadFileControl1.IsColse = False
        UploadFileControl1.InitDataAndShow()
    End Sub

    '查詢
    Protected Sub btnQuery_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnQuery.Click


        Me.BindGV()
    End Sub


    Protected Sub fv_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles fv.DataBound
        Me.BindTownID()
        Me.BindDirtyItemForInsert()

        TryCast(Me.fv.FindControl("SelfRegionType1"), WebForm_SelfManageWorkHeader_SelfRegionType).BindgvRegionType()

        If Me.fv.CurrentMode = FormViewMode.Edit Then
            '通報日期
            TryCast(Me.fv.FindControl("txtReportDate"), WebForm_CommonControl_CalendarTextBox).Value = Convert.ToDateTime(DataBinder.Eval(Me.fv.DataItem, "ReportDate").ToString()).Date

            '清查地點
            Dim ddlItem As DropDownList
            ddlItem = TryCast(Me.fv.FindControl("ddlTownID"), DropDownList)
            ddlItem.SelectedIndex = ddlItem.Items.IndexOf(ddlItem.Items.FindByValue(DataBinder.Eval(Me.fv.DataItem, "RegionID").ToString()))
            BindVillageID()
            ddlItem = TryCast(Me.fv.FindControl("ddlVillageID"), DropDownList)
            ddlItem.SelectedIndex = ddlItem.Items.IndexOf(ddlItem.Items.FindByValue(DataBinder.Eval(Me.fv.DataItem, "VillageID").ToString()))
            '髒亂地區類別
            TryCast(Me.fv.FindControl("SelfRegionType1"), WebForm_SelfManageWorkHeader_SelfRegionType).BindRegionItem(DataBinder.Eval(Me.fv.DataItem, "RegionType").ToString())

            '繫結GoogleMap
            TryCast(Me.fv.FindControl("GoogleMapExif1"), WebForm_CommonControl_GoogleMapExif).PicFilePath = DataBinder.Eval(Me.fv.DataItem, "PhotoFullPath").ToString()

        End If

    End Sub

    Protected Sub gvDirtyItem_DataBound(ByVal sender As Object, ByVal e As System.EventArgs)
        '將項目名稱相同者做 RowSpan
        Dim i As Integer = 1

        Dim GridView_Master As GridView = TryCast(Me.fv.FindControl("gvDirtyItem"), GridView)


        For Each wkItem As GridViewRow In GridView_Master.Rows
            If wkItem.RowIndex <> 0 Then
                Dim firstSubRow As Integer = wkItem.RowIndex - i
                Dim s1 As String = DirectCast(wkItem.FindControl("lblDirtyItemName"), Label).Text.Trim()
                Dim s2 As String = DirectCast(GridView_Master.Rows(firstSubRow).FindControl("lblDirtyItemName"), Label).Text.Trim()

                If s1 = s2 Then
                    GridView_Master.Rows(firstSubRow).Cells(0).RowSpan += 1
                    wkItem.Cells(0).Visible = False
                    i = i + 1
                Else
                    GridView_Master.Rows((wkItem.RowIndex)).Cells(0).RowSpan += 1

                    i = 1

                End If
            Else

                wkItem.Cells(0).RowSpan = 1
            End If
        Next
    End Sub

    Protected Sub gvDirtyItem_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
        If e.Row.RowType = DataControlRowType.DataRow Then

            Dim item As New ListItem
            item.Text = TryCast(e.Row.FindControl("lblSubText"), Label).Text
            item.Value = TryCast(e.Row.FindControl("lblSubValue"), Label).Text
            TryCast(e.Row.FindControl("cbList"), CheckBoxList).Items.Add(item)

            Me.BindDirtyLevel(TryCast(e.Row.FindControl("ddlDirtyLevel"), DropDownList))

            If Me.fv.CurrentMode = FormViewMode.ReadOnly Then
                TryCast(e.Row.FindControl("ddlDirtyLevel"), DropDownList).Enabled = False
            End If
        End If
    End Sub

    Protected Sub btnApprove_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnApprove.Click
        Me.Approved = True
        Me.btnSave_Click(Nothing, Nothing)
    End Sub
    Protected Sub btnUpdateHour_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdateHour.Click
        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        Using scope As New Transactions.TransactionScope
            sql.AppendFormat("update whr set WorkHour = '{0}' ", Integer.Parse(Me.txtDefaultWorkHour.Text))
            sql.AppendFormat("from WorkHourRecord whr ")
            sql.AppendFormat("inner join WorkRecord wr on whr.RecordID = wr.RecordID and whr.WorkType = '{0}' ", "FindDirtyHeader")
            sql.AppendFormat("inner join WorkHeader wh on wr.WorkHeaderID = wh.WorkHeaderID ")

            sql.AppendFormat(" Where wh.WorkHeaderID = '{0}' ", Me.WorkHeaderID)
            dat.AccData(sql)

            scope.Complete()
        End Using

        Me.BindGV()
    End Sub
#Region "存檔"

    Public Event Save_Click(ByVal source As Object, ByVal e As EventArgs)

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        If Page.IsValid = False Then
            Return
        End If

        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        Dim i As Integer

        Dim MyWorkHeaderID As Integer

        Dim FormView_WorkHeader As FormView
        Dim startHour As Integer
        Dim EndHour As Integer
        Dim workStartDate As Date
        Dim workEndDate As Date

        If Me.DataAccessMode <> FormDataAccessMode.Take Then
            FormView_WorkHeader = AddWorkHeaderControl1.FindControl("FormView_WorkHeader")

            startHour = CInt(TryCast(FormView_WorkHeader.FindControl("SelectTimeStart"), WebForm_ReserveCar_SelectTime).Text)
            EndHour = CInt(TryCast(FormView_WorkHeader.FindControl("SelectTimeEnd"), WebForm_ReserveCar_SelectTime).Text)

            If startHour = 24 Then
                startHour = 0
            End If

            If EndHour = 24 Then
                EndHour = 0
            End If

            workStartDate = TryCast(FormView_WorkHeader.FindControl("txtWorkStartDate"), WebForm_CommonControl_CalendarTextBox).Value.AddHours(startHour)
            workEndDate = TryCast(FormView_WorkHeader.FindControl("txtWorkStartDate"), WebForm_CommonControl_CalendarTextBox).Value.AddHours(EndHour)

            If Me.CanAdmin = False AndAlso clsAuth.IsInCloseDate(workStartDate, workEndDate, Me.AddLeader1.TakeDate) = False Then
                MyObj.ShowMessage("已過關帳日")
                Return
            End If
        End If

        Using scope As New Transactions.TransactionScope



            If DataAccessMode = FormDataAccessMode.Take Then
                '存檔-WorkHeader
                If WorkHeaderID <> 0 Then
                    sql.AppendFormat("UPdate WorkHeader Set ")
                    sql.AppendFormat("CreateType='{0}' ", "P")
                    sql.AppendFormat(",UOrganizationID='{0}' ", Me.AddLeader1.UOrganizationID)
                    sql.AppendFormat(",VUOrganizationID='{0}' ", Me.AddLeader1.VOrganizationID)
                    sql.AppendFormat(",LeaderID='{0}' ", Me.AddLeader1.VolunteerID)
                    sql.AppendFormat(",CreateDate=getdate() ")
                    sql.AppendFormat(",CreateBy='{0}' ", clsAuth.GetUserID())
                    sql.AppendFormat(",TakeDate='{0:yyyy/MM/dd HH:mm}' ", Me.AddLeader1.TakeDate)
                    sql.AppendFormat(",Active='{0}' ", "N")
                    sql.AppendFormat("Where WorkHeaderID='{0}' ", WorkHeaderID)
                Else
                    sql.AppendFormat("INSERT WorkHeader (CreateType,UOrganizationID,VUOrganizationID,LeaderID,CreateDate,CreateBy,TakeDate,Active) ")
                    sql.AppendFormat("SELECT 'P' ")
                    sql.AppendFormat(",'{0}' ", Me.AddLeader1.UOrganizationID)
                    sql.AppendFormat(",'{0}' ", Me.AddLeader1.VOrganizationID)
                    sql.AppendFormat(",'{0}' ", Me.AddLeader1.VolunteerID)

                    sql.AppendFormat(", getdate()")
                    sql.AppendFormat(", '{0}' ", Page.User.Identity.Name)
                    sql.AppendFormat(", '{0:yyyy/MM/dd HH:mm}' ", Me.AddLeader1.TakeDate)
                    sql.AppendFormat(", '{0}'; ", "N")

                End If

                dat.AccData(sql)


                'MyWorkHeaderID是local變數
                If WorkHeaderID = 0 Then
                    Me.WorkHeaderID = MyObj.GetIdentity()
                End If
                MyWorkHeaderID = Me.WorkHeaderID
             
                sql.Length = 0

                sql.AppendFormat("UPDATE FindDirtyHeader ")
                sql.AppendFormat("SET WorkHeaderID='{0}' ", MyWorkHeaderID)
                sql.AppendFormat("WHERE FindDirtyHeaderID='{0}';", FindDirtyHeaderID)

                'sql.AppendFormat("UPDATE WorkRecord ")
                'sql.AppendFormat("SET WorkHeaderID = {0}", MyWorkHeaderID)
                'sql.AppendFormat("WHERE WorkHeaderID = 0 and CreateBy='{0}';", Page.User.Identity.Name)

                'sql.AppendFormat("UPDATE UploadFiles ")
                'sql.AppendFormat("SET theType = '{0}'", MyWorkHeaderID)
                'sql.AppendFormat("WHERE theType = '0' and CreateBy='{0}';", Page.User.Identity.Name)

                '儲存處理前後照片

                'Me.AddWorkHeaderControl1.WorkHeaderID = Me.WorkHeaderID
                'Me.AddWorkHeaderControl1.SavePhoto()

                'sql.AppendFormat("UPDATE WorkHeader set ")
                'sql.AppendFormat("PreExecutionPhotoName = '{0}'", Me.AddWorkHeaderControl1.PreExecutionPhotoName)
                'sql.AppendFormat(",PostExecutionPhotoName = '{0}'", Me.AddWorkHeaderControl1.PostExecutionPhotoName)
                'sql.AppendFormat("WHERE WorkHeaderID = '{0}';", Me.WorkHeaderID)
            Else 'If DataAccessMode = FormViewMode.Edit Then
                '存檔-WorkHeader

                sql.AppendFormat("UPDATE WorkHeader ")
                'sql.AppendFormat("SET UOrganizationID='{0}' ", Me.AddWorkHeaderControl1.UOrganizationID)
                'sql.AppendFormat(",VUOrganizationID='{0}' ", Me.AddWorkHeaderControl1.VOrganizationID)
                'sql.AppendFormat(",LeaderID='{0}' ", Me.AddWorkHeaderControl1.VolunteerID)
                sql.AppendFormat("SET UOrganizationID='{0}' ", Me.AddLeader1.UOrganizationID)
                sql.AppendFormat(",VUOrganizationID='{0}' ", Me.AddLeader1.VOrganizationID)
                sql.AppendFormat(",LeaderID='{0}' ", Me.AddLeader1.VolunteerID)
                sql.AppendFormat(",PeopleJoined='{0}' ", TryCast(FormView_WorkHeader.FindControl("txtPeopleJoined"), TextBox).Text)
                sql.AppendFormat(",WorkStartDate='{0:yyyy/MM/dd HH:mm} ' ", workStartDate)
                sql.AppendFormat(",WorkEndDate='{0:yyyy/MM/dd HH:mm}' ", workEndDate)
                sql.AppendFormat(",WorkHour='{0}' ", TryCast(FormView_WorkHeader.FindControl("txtWorkHour"), TextBox).Text)
                sql.AppendFormat(",Active='{0}' ", IIf(Me.Approved = True, "Y", "N"))

                '判斷是否選擇其他
                If TryCast(FormView_WorkHeader.FindControl("rbListCleanPeopleType"), RadioButtonList).SelectedItem.Text = "其他" Then
                    sql.AppendFormat(",CleanPeopleType='{0}' ", TryCast(FormView_WorkHeader.FindControl("txtOther"), TextBox).Text)
                Else
                    sql.AppendFormat(",CleanPeopleType='{0}' ", TryCast(FormView_WorkHeader.FindControl("rbListCleanPeopleType"), RadioButtonList).SelectedItem.Text)
                End If

                sql.AppendFormat(",UpdateDate=getdate() ")
                sql.AppendFormat(",UpdateBy='{0}' ", Page.User.Identity.Name)

                sql.AppendFormat("WHERE WorkHeaderID='{0}'; ", WorkHeaderID)

                If Me.Approved = True Then
                    '獎勵
                    sql.AppendFormat("INSERT workhourrecord (RecordID,WorkType,VolunteerID,WorkHour,WorkTimes,Active,EffectiveDate,CreateDate,CreateBy) ")
                    sql.AppendFormat("SELECT {0} ", FindDirtyHeaderID)
                    sql.AppendFormat(",'FindDirtyAward' ")
                    sql.AppendFormat(",(SELECT CreateBy FROM FindDirtyHeader WHERE FindDirtyHeaderID={0})", FindDirtyHeaderID)
                    sql.AppendFormat(",(SELECT ParameterValue FROM SystemParameter WHERE ParameterType='WorkHourRecord' AND ParameterName='FindDirtyHeaderAward') ")
                    sql.AppendFormat(",1,'Y',getdate(),getdate(),'{0}' ; ", Page.User.Identity.Name)
                End If

                MyWorkHeaderID = WorkHeaderID

                '修改清潔內容
                '步驟一:先將該服務計畫底下的清潔內容刪除
                '步驟二:再將清潔內容新增到 WorkItem
                sql.AppendFormat("delete from workitem where workHeaderID='{0}'; ", MyWorkHeaderID)

                Dim workitem As DataTable = Me.AddWorkItemControl1.GetWorkItem()
                For k As Integer = 0 To workitem.Rows.Count - 1
                    sql.AppendFormat("Insert workItem(WorkHeaderID,ItemGroupID,ItemID,Amount) ")
                    sql.AppendFormat("Select '{0}' ", MyWorkHeaderID)
                    sql.AppendFormat(",'{0}' ", workitem.Rows(k)("ItemGroupID").ToString)
                    sql.AppendFormat(",'{0}' ", workitem.Rows(k)("ItemID").ToString)
                    sql.AppendFormat(",'{0}'; ", workitem.Rows(k)("Amount").ToString())

                Next

                '儲存處理前後照片

                'Me.AddWorkHeaderControl1.WorkHeaderID = Me.WorkHeaderID
                'Me.AddWorkHeaderControl1.SavePhoto()

                'sql.AppendFormat("UPDATE WorkHeader set ")
                'sql.AppendFormat("PreExecutionPhotoName = '{0}'", Me.AddWorkHeaderControl1.PreExecutionPhotoName)
                'sql.AppendFormat(",PostExecutionPhotoName = '{0}'", Me.AddWorkHeaderControl1.PostExecutionPhotoName)
                'sql.AppendFormat("WHERE WorkHeaderID = '{0}';", Me.WorkHeaderID)
            End If

            For Each gvr As GridViewRow In GridView_VolunteersDirty.Rows

                'Dim cblCheckStatus As CheckBoxList = gvr.FindControl("cblCheckStatus")
                Dim chkSignIn As CheckBox = TryCast(gvr.FindControl("chkSignIn"), CheckBox)
                Dim chkSignOut As CheckBox = TryCast(gvr.FindControl("chkSignOut"), CheckBox)

                i = 0

                If chkSignIn.Checked = True Then
                    i += 1
                End If

                If chkSignOut.Checked = True Then
                    i += 2
                End If

                Dim strFlag As String = "N"

                If i >= 3 Then
                    strFlag = "Y"
                Else
                    strFlag = "N"
                End If

                If DataAccessMode = FormDataAccessMode.Take Then

                    sql.AppendFormat("UPDATE WorkRecord SET Status={0} WHERE RecordID={1};", i, GridView_VolunteersDirty.DataKeys(gvr.RowIndex).Value)
                    sql.AppendFormat("UPDATE WorkHourRecord SET Active='{0}',CreateDate=getdate() WHERE RecordID={1} and WorkType='FindDirtyHeader';", "N", GridView_VolunteersDirty.DataKeys(gvr.RowIndex).Value)

                Else
                    Dim active As String

                    If strFlag = "Y" And Me.Approved = True Then
                        active = "Y"
                    Else
                        active = "N"
                    End If

                    sql.AppendFormat("UPDATE WorkRecord SET Status={0},UpdateDate=getdate() WHERE RecordID={1};", i, GridView_VolunteersDirty.DataKeys(gvr.RowIndex).Value)
                    '第一次審核記錄時數生效日期

                    If active = "N" Then
                        sql.AppendFormat("UPDATE WorkHourRecord SET UpdateDate = getdate(),Updateby= '{0}' where RecordID={1} and Active = 'N' ", clsAuth.GetUserID(), GridView_VolunteersDirty.DataKeys(gvr.RowIndex).Value)
                    End If
                    sql.AppendFormat("UPDATE WorkHourRecord SET Active='{0}' WHERE RecordID={1} and WorkType='CleanPlan';", active, GridView_VolunteersDirty.DataKeys(gvr.RowIndex).Value)

                    ' sql.AppendFormat("UPDATE WorkHourRecord SET EffectiveDate = getdate() where RecordID={0} and Active = 'N' ", GridView_VolunteersDirty.DataKeys(gvr.RowIndex).Value)
                    If active = "Y" Then
                        sql.AppendFormat("UPDATE WorkHourRecord SET EffectiveDate = getdate(),EffectiveBy = '{0}' where RecordID={1} and WorkType='CleanPlan'; ", clsAuth.GetUserID(), GridView_VolunteersDirty.DataKeys(gvr.RowIndex).Value)
                    End If

                End If


            Next

            If sql.Length <> 0 Then
                dat.AccData(sql)
                MyObj.ShowMessage(Me.GetLocalResourceObject("SaveOK"))
            End If

            scope.Complete()

        End Using

        RaiseEvent Save_Click(Me, New EventArgs)

    End Sub

    Public Function EcolifeInsert(ByVal EcolifeCaseNo As String) As String
        Dim dat As New clsData
        Dim sql As New MyStringBuilder
        Dim dt As DataTable

        Dim i As Integer

        Dim MyWorkHeaderID As Integer

        sql.AppendFormat("select a.WorkHeaderID from WorkHeader a join FindDirtyHeader b ")
        sql.AppendFormat("on a.WorkHeaderID=b.WorkHeaderID ")
        sql.AppendFormat("where a.EcolifeCaseNo='{0}' ", EcolifeCaseNo)
        dt = dat.GetData(sql.ToString())

        If dt.Rows.Count > 0 Then
            MyWorkHeaderID = dt.Rows(0)("WorkHeaderID")
            Me.WorkHeaderID = MyWorkHeaderID
        Else
            Using scope As New Transactions.TransactionScope
                sql.Length = 0

                '存檔-WorkHeader
                sql.AppendFormat("INSERT WorkHeader (CreateType,EcolifeCaseNo,UOrganizationID,VUOrganizationID,LeaderID,CreateDate,CreateBy,TakeDate,Active) ")
                sql.AppendFormat("SELECT 'P' ")
                sql.AppendFormat(",'{0}' ", EcolifeCaseNo)
                sql.AppendFormat(",'{0}' ", Me.AddLeader1.UOrganizationID)
                sql.AppendFormat(",'{0}' ", Me.AddLeader1.VOrganizationID)
                sql.AppendFormat(",'{0}' ", Me.AddLeader1.VolunteerID)

                sql.AppendFormat(", getdate()")
                sql.AppendFormat(", '{0}' ", Page.User.Identity.Name)
                sql.AppendFormat(", '{0:yyyy/MM/dd HH:mm}' ", Me.AddLeader1.TakeDate)
                sql.AppendFormat(", '{0}' ", "N")

                dat.AccData(sql)

                'MyWorkHeaderID是local變數
                MyWorkHeaderID = MyObj.GetIdentity()
                Me.WorkHeaderID = MyObj.GetIdentity()

                sql.Length = 0

                sql.AppendFormat("UPDATE FindDirtyHeader ")
                sql.AppendFormat("SET WorkHeaderID='{0}' ", MyWorkHeaderID)
                sql.AppendFormat("WHERE FindDirtyHeaderID='{0}';", FindDirtyHeaderID)

                sql.AppendFormat("UPDATE WorkRecord ")
                sql.AppendFormat("SET WorkHeaderID = {0}", MyWorkHeaderID)
                sql.AppendFormat("WHERE WorkHeaderID = 0 and CreateBy='{0}';", Page.User.Identity.Name)

                sql.AppendFormat("UPDATE UploadFiles ")
                sql.AppendFormat("SET theType = '{0}'", MyWorkHeaderID)
                sql.AppendFormat("WHERE theType = '0' and CreateBy='{0}';", Page.User.Identity.Name)

                For Each gvr As GridViewRow In GridView_VolunteersDirty.Rows

                    'Dim cblCheckStatus As CheckBoxList = gvr.FindControl("cblCheckStatus")
                    Dim chkSignIn As CheckBox = TryCast(gvr.FindControl("chkSignIn"), CheckBox)
                    Dim chkSignOut As CheckBox = TryCast(gvr.FindControl("chkSignOut"), CheckBox)

                    i = 0

                    If chkSignIn.Checked = True Then
                        i += 1
                    End If

                    If chkSignOut.Checked = True Then
                        i += 2
                    End If

                    Dim strFlag As String = "N"

                    If i >= 3 Then
                        strFlag = "Y"
                    Else
                        strFlag = "N"
                    End If

                    If DataAccessMode = FormDataAccessMode.Take Then

                        sql.AppendFormat("UPDATE WorkRecord SET Status={0} WHERE RecordID={1};", i, GridView_VolunteersDirty.DataKeys(gvr.RowIndex).Value)
                        sql.AppendFormat("UPDATE WorkHourRecord SET Active='{0}',CreateDate=getdate() WHERE RecordID={1} and WorkType='FindDirtyHeader';", "N", GridView_VolunteersDirty.DataKeys(gvr.RowIndex).Value)

                    Else
                        Dim active As String

                        If strFlag = "Y" And Me.Approved = True Then
                            active = "Y"
                        Else
                            active = "N"
                        End If

                        sql.AppendFormat("UPDATE WorkRecord SET Status={0},UpdateDate=getdate() WHERE RecordID={1};", i, GridView_VolunteersDirty.DataKeys(gvr.RowIndex).Value)
                        '第一次審核記錄時數生效日期
                        If active = "N" Then
                            sql.AppendFormat("UPDATE WorkHourRecord SET UpdateDate = getdate(),Updateby= '{0}' where RecordID={1} and Active = 'N' ", clsAuth.GetUserID(), GridView_VolunteersDirty.DataKeys(gvr.RowIndex).Value)
                        End If
                        sql.AppendFormat("UPDATE WorkHourRecord SET Active='{0}' WHERE RecordID={1} and WorkType='CleanPlan';", active, GridView_VolunteersDirty.DataKeys(gvr.RowIndex).Value)

                        ' sql.AppendFormat("UPDATE WorkHourRecord SET EffectiveDate = getdate() where RecordID={0} and Active = 'N' ", GridView_VolunteersDirty.DataKeys(gvr.RowIndex).Value)
                        If active = "Y" Then
                            sql.AppendFormat("UPDATE WorkHourRecord SET EffectiveDate = getdate(),EffectiveBy = '{0}' where RecordID={1} and WorkType='CleanPlan'; ", clsAuth.GetUserID(), GridView_VolunteersDirty.DataKeys(gvr.RowIndex).Value)
                        End If

                    End If


                Next

                If sql.Length <> 0 Then
                    dat.AccData(sql)
                End If

                'Ecolife資料自動帶入
                '==============================================================================
                '自動帶入清理時間
                sql.Length = 0
                sql.AppendFormat("select CleanDateStart,CleanDateEnd from EcolifeDataView ")
                sql.AppendFormat("where CaseNo='{0}'", EcolifeCaseNo)
                dt = dat.GetData(sql)
                If dt.Rows.Count > 0 Then
                    sql.Length = 0
                    sql.AppendFormat("update WorkHeader set ")
                    sql.AppendFormat("WorkStartDate='{0:yyyy/MM/dd HH:mm:ss}' ", dt.Rows(0)("CleanDateStart"))
                    sql.AppendFormat(",WorkEndDate='{0:yyyy/MM/dd HH:mm:ss}' ", dt.Rows(0)("CleanDateStart"))
                    sql.AppendFormat("where WorkHeaderID='{0}' ", MyWorkHeaderID)
                    dat.AccData(sql.ToString)
                End If

                '自動帶入通報物件
                sql.Length = 0
                sql.AppendFormat("select a.Count,b.TableName,b.Value from EcolifeItemView a ")
                sql.AppendFormat("join EcolifeItemMapping b ")
                sql.AppendFormat("on a.ItemName=b.ItemName ")
                sql.AppendFormat("where a.CaseNo='{0}'", EcolifeCaseNo)
                dt = dat.GetData(sql)

                If dt.Rows.Count > 0 Then
                    For j As Integer = 0 To dt.Rows.Count - 1
                        Dim dt2 As DataTable
                        sql.Length = 0
                        sql.AppendFormat("select a.Value as ItemID,b.Value as ItemGroupID from CodeMapping a ")
                        sql.AppendFormat("join CodeMapping b ")
                        sql.AppendFormat("on b.TableName+'_'+b.ColumnName+'_'+b.Value=a.TableName ")
                        sql.AppendFormat("where a.TableName='{0}' ", dt.Rows(i)("TableName"))
                        sql.AppendFormat("and a.Value='{0}' ", dt.Rows(i)("Value"))
                        dt2 = dat.GetData(sql)

                        If dt2.Rows.Count > 0 Then
                            sql.Length = 0
                            sql.AppendFormat("Insert workItem(WorkHeaderID,ItemGroupID,ItemID,Amount) ")
                            sql.AppendFormat("Select '{0}' ", MyWorkHeaderID)
                            sql.AppendFormat(",'{0}' ", dt2.Rows(0)("ItemGroupID").ToString)
                            sql.AppendFormat(",'{0}' ", dt2.Rows(0)("ItemID").ToString)
                            sql.AppendFormat(",'{0}';", dt.Rows(0)("Count").ToString())
                            dat.AccData(sql)
                        End If
                    Next
                End If
                '==============================================================================

                scope.Complete()

            End Using
        End If

        Return MyWorkHeaderID
    End Function
#End Region

#Region "DataBinding-將值分散"
    Protected Sub cblCheckStatus_DataBinding(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim cblCheckStatus As CheckBoxList = sender
        Dim gvr As GridViewRow = cblCheckStatus.NamingContainer

        Dim CheckStatus As Integer = DataBinder.Eval(gvr.DataItem, "Status").ToString()

        If CheckStatus = 1 Then
            cblCheckStatus.Items(0).Selected = True
            cblCheckStatus.Items(1).Selected = False
        ElseIf CheckStatus = 2 Then
            cblCheckStatus.Items(0).Selected = False
            cblCheckStatus.Items(1).Selected = True
        ElseIf CheckStatus = 3 Then
            cblCheckStatus.Items(0).Selected = True
            cblCheckStatus.Items(1).Selected = True
        Else
            cblCheckStatus.Items(0).Selected = False
            cblCheckStatus.Items(1).Selected = False
        End If

    End Sub

#End Region

#Region "儲存志工"
    Private Function SavePerson() As Boolean

        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        Using scope As New Transactions.TransactionScope

            For Each VolunteerID As String In Me.SearchVolunteerControl_AddDirtyHeader1.SelectedValues

                sql.AppendFormat("INSERT WorkRecord (WorkHeaderID,Status,CreateDate,CreateBy) ")
                sql.AppendFormat("SELECT {0}", WorkHeaderID)
                sql.AppendFormat(", '{0}'", 0)
                sql.AppendFormat(", getdate()")
                sql.AppendFormat(", '{0}'; ", Me.Page.User.Identity.Name)

                sql.AppendFormat("INSERT WorkHourRecord (RecordID,WorkType,VolunteerID,WorkHour,WorkTimes,Active,CreateDate,CreateBy) ")
                sql.AppendFormat("SELECT @@IDENTITY")
                sql.AppendFormat(", 'FindDirtyHeader'")
                sql.AppendFormat(", '{0}'", VolunteerID)
                sql.AppendFormat(", '{0}'", txtDefaultWorkHour.Text)
                sql.AppendFormat(", '{0}'", txtDefaultWorkTimes.Text)
                sql.AppendFormat(", 'N'")

                If DataAccessMode = FormDataAccessMode.Take Then
                    sql.AppendFormat(", null")
                ElseIf DataAccessMode = FormDataAccessMode.Execute Or DataAccessMode = FormDataAccessMode.Approve Then
                    sql.AppendFormat(", getdate()")
                End If

                sql.AppendFormat(", '{0}'; ", Me.Page.User.Identity.Name)

            Next

            If sql.Length <> 0 Then
                dat.AccData(sql)
            End If

            scope.Complete()

        End Using

        Return True

    End Function
#End Region

#Region "CheckBox全選"
    '刪除
    Protected Sub chkAlldelete_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim chkAll As CheckBox = TryCast(sender, CheckBox)

        For Each row As GridViewRow In Me.GridView_VolunteersDirty.Rows
            Dim chk As CheckBox = TryCast(row.FindControl("chkdelete"), CheckBox)

            chk.Checked = chkAll.Checked
        Next

    End Sub
    Protected Sub chkAllSignIn_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim chkAll As CheckBox = TryCast(sender, CheckBox)

        For Each row As GridViewRow In Me.GridView_VolunteersDirty.Rows
            Dim chk As CheckBox = TryCast(row.FindControl("chkSignIn"), CheckBox)

            chk.Checked = chkAll.Checked
        Next

    End Sub

    Protected Sub chkAllSignOut_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim chkAll As CheckBox = TryCast(sender, CheckBox)

        For Each row As GridViewRow In Me.GridView_VolunteersDirty.Rows
            Dim chk As CheckBox = TryCast(row.FindControl("chkSignOut"), CheckBox)

            chk.Checked = chkAll.Checked
        Next

    End Sub
#End Region
  

#Region "匯出簽到表"
    Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExport.Click
        Dim GV As New GridView
        Dim ResultDataTable As DataTable
        Dim dat As New clsData

        Dim sqlParams As SqlParameter() = New SqlParameter(0) {}

        sqlParams(0) = New SqlParameter("@WorkHeaderID", SqlDbType.Int)
        sqlParams(0).Value = WorkHeaderID
        ResultDataTable = dat.GetData("GetVolunteerRegisterTable_FindDirtyHeader", sqlParams, CommandType.StoredProcedure, "ResultTable").Tables.Item(0)

        If ResultDataTable IsNot Nothing AndAlso ResultDataTable.Rows.Count > 0 Then
            'Prepare Data

            Dim base As Integer = 15

            Dim vList As New List(Of DirtyHeader)
            Dim v As DirtyHeader


            'For i As Integer = 1 To base

            Dim i As Integer = 1
            Dim prevRegionID As String

            For Each dr As DataRow In ResultDataTable.Rows
                If prevRegionID <> "" AndAlso prevRegionID <> dr("VOrganizationName") Then

                    For j As Integer = (i Mod base) To base
                        v = New DirtyHeader
                        v.Name = ""
                        v.VOrganizationName = ""
                        v.Index = i
                        v.RegStatus = ""
                        vList.Add(v)

                        i = i + 1
                    Next

                    i = 1
                End If

                v = New DirtyHeader
                v.Name = dr("VolunteerName").ToString()
                v.VOrganizationName = dr("VOrganizationName").ToString()
                'v.RegStatus = dr("RegStatusText").ToString()
                v.RegStatus = ""
                v.Index = i
                vList.Add(v)

                If i Mod base = 1 Then
                    v.IsHeader = True
                Else
                    v.IsHeader = False
                End If

                i += 1
                prevRegionID = dr("VOrganizationName")

            Next

            For j As Integer = (i Mod base) To base
                v = New DirtyHeader
                v.Name = ""
                v.VOrganizationName = ""
                v.Index = i
                v.RegStatus = ""
                vList.Add(v)

                i = i + 1
            Next

            'Print

            Dim fileName As String = "DirtyHeader.xls"
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName)
            Response.ContentType = "application/vnd.ms-excel"

            Dim velocity As New VelocityEngine
            Dim props As New Commons.Collections.ExtendedProperties

            'fix bug
            props.AddProperty("file.resource.loader.path", Server.MapPath("~\App_Data"))
            props.AddProperty("input.encoding", "utf-8")
            props.AddProperty("output.encoding", "utf-8")
            velocity.Init(props)

            Dim template As Template

            Dim context As New VelocityContext

            template = velocity.GetTemplate("服務時數簽到表v2.xml")
            context.Put("OrganizationName", Me.ddlTownID.SelectedItem.Text)
            context.Put("LeaderName", Me.AddLeader1.LeaderName)
            context.Put("LeaderOrg", Me.AddLeader1.VOrgName)
            context.Put("PlanName", txtDirtyHeaderName.Text.Trim())
            context.Put("PrintRowCount", vList.Count + 5)
            context.Put("VolunteerList", vList)
            context.Put("User", clsAuth.GetUserID())
            context.Put("DownloadDate", Today.Year.ToString() & "-" & Today.Month.ToString() & "-" & Today.Day.ToString() & "T" & Now.Hour.ToString() & ":" & Now.Minute.ToString() & ":" & Now.Second.ToString() & "Z")
            context.Put("IP", MyObj.getIP())

            Dim writer As New IO.StringWriter
            template.Merge(context, writer)

            Response.Write(writer.GetStringBuilder().ToString())

            Response.End()

            'GV.AutoGenerateColumns = False

            'GV.Caption = String.Format(Me.GetLocalResourceObject("Caption"), ResultDataTable.Rows.Item(0).Item("TheYear"), ResultDataTable.Rows.Item(0).Item("PlanName"), ResultDataTable.Rows.Item(0).Item("StartDate"))

            'MyObj.AddBoundField(GV, "sn", Me.GetLocalResourceObject("sn"))
            'MyObj.AddBoundField(GV, "RegionName", Me.GetLocalResourceObject("RegionName"))
            'MyObj.AddBoundField(GV, "VolunteerName", Me.GetLocalResourceObject("VolunteerName_Excel"))
            'MyObj.AddBoundField(GV, "Birthday", Me.GetLocalResourceObject("Birthday"))
            'MyObj.AddBoundField(GV, "VolunteerID", Me.GetLocalResourceObject("VolunteerID_Excel"))
            'MyObj.AddBoundField(GV, "", Me.GetLocalResourceObject("c1"))
            'MyObj.AddBoundField(GV, "", Me.GetLocalResourceObject("c2"))
            'MyObj.AddBoundField(GV, "", Me.GetLocalResourceObject("c3"))
            'MyObj.AddBoundField(GV, "", Me.GetLocalResourceObject("c4"))

            'GV.Columns.Item(0).ItemStyle.HorizontalAlign = HorizontalAlign.Center
            'GV.Columns.Item(5).ItemStyle.Width = Unit.Pixel(95)
            'GV.Columns.Item(6).ItemStyle.Width = Unit.Pixel(95)

            'GV.DataSource = ResultDataTable
            'GV.DataBind()

            'GV.Page = Me.Page

            'MyObj.ExportToExcel(GV, Server.UrlEncode(String.Format("{0}-髒亂點簽到表.xls", ResultDataTable.Rows.Item(0).Item("PlanName"))))

        Else

            MyObj.ShowMessage(Me.GetLocalResourceObject("NoData"))

        End If
    End Sub

    Public Class DirtyHeader
        Private NameField As String
        Private VOrganizationNameField As String

        Private IndexField As Integer
        Private IsHeaderField As Boolean

        Public Property Name() As String
            Get
                Return Me.NameField
            End Get
            Set(ByVal value As String)
                Me.NameField = value
            End Set
        End Property
        Public Property VOrganizationName() As String
            Get
                Return Me.VOrganizationNameField
            End Get
            Set(ByVal value As String)
                Me.VOrganizationNameField = value
            End Set
        End Property



        Public WriteOnly Property IsHeader() As Boolean
            Set(ByVal value As Boolean)
                Me.IsHeaderField = value
            End Set
        End Property

        Public ReadOnly Property CellText() As String
            Get
                If Me.IsHeaderField = True Then
                    Return "<Cell ss:MergeDown=""15"" ss:StyleID=""s52""><Data ss:Type=""String""></Data><NamedCell ss:Name=""Print_Area""/></Cell>"
                Else
                    Return ""
                End If
            End Get
        End Property

        Public ReadOnly Property CellText2() As String
            Get
                If Me.IsHeaderField = True Then
                    Return ""
                Else
                    Return "ss:Index=""2"""
                End If
            End Get
        End Property

        Public Property Index() As Integer
            Get
                Return Me.IndexField
            End Get
            Set(ByVal value As Integer)
                Me.IndexField = value
            End Set
        End Property

        Private RegStatusField As String

        Public Property RegStatus() As String
            Get
                Return Me.RegStatusField
            End Get
            Set(ByVal value As String)
                Me.RegStatusField = value
            End Set
        End Property

    End Class
#End Region

#Region "刪除"

    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim sql As New MyStringBuilder
        Dim dat As New clsData

        Dim SaveRecordID As New List(Of String)
        For Each row As GridViewRow In Me.GridView_VolunteersDirty.Rows
            Dim key As DataKey = Me.GridView_VolunteersDirty.DataKeys(row.RowIndex)
            If TryCast(row.FindControl("chkdelete"), CheckBox).Checked = True Then
                SaveRecordID.Add(key("RecordID"))
            End If
        Next

        If SaveRecordID.Count > 0 Then
            Dim RecordIDString As String = ""
            RecordIDString = Regex.Replace(String.Join(",", SaveRecordID.ToArray()), "(\d+)", "'$1'")
            sql.Length = 0
            sql.AppendFormat("Delete from WorkRecord where RecordID in ({0}); ", RecordIDString)
            sql.AppendFormat("Delete from WorkHourRecord where RecordID in ({0}); ", RecordIDString)
            dat.AccData(sql)
            MyObj.ShowMessage("刪除成功!")
            Me.BindGV()
        Else
            MyObj.ShowMessage("您沒有勾選任何要刪除的資料!!")
        End If
    End Sub
#End Region

#Region "更新"
    Protected Sub btnUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdate.Click

        Dim sql As New MyStringBuilder
        Dim dat As New clsData
        sql.Length = 0
        For Each row As GridViewRow In Me.GridView_VolunteersDirty.Rows
            Dim key As DataKey = Me.GridView_VolunteersDirty.DataKeys(row.RowIndex)
            sql.AppendFormat("Update WorkHourRecord Set ")
            sql.AppendFormat("WorkHour='{0}' ", TryCast(row.FindControl("txtWorkHour"), TextBox).Text.Trim())
            sql.AppendFormat("where RecordID ='{0}'; ", key("RecordID"))
        Next

        dat.AccData(sql)
        MyObj.ShowMessage("更新成功!")
        Me.BindGV()
    End Sub
#End Region



    Public Sub BindGV()
        Dim dt As DataTable = wrManager.AddDirtyGetData(WorkHeaderID, VolunteerQueryControl1.OrganizationID, VolunteerQueryControl1.VOrganizationID, VolunteerQueryControl1.VolunteerId, VolunteerQueryControl1.VolunteerName, VolunteerQueryControl1.VolunteerTEL)
        Dim Count As Integer = dt.Rows.Count
        If GridView_VolunteersDirty.SortSQL <> "" Then
            dt.DefaultView.Sort = GridView_VolunteersDirty.SortSQL
            dt = dt.DefaultView.ToTable()
        End If
        Me.lblTotal.Text = IIf(Count > 0, Count & Space(1) & "records", "")
        GridView_VolunteersDirty.DataSource = dt
        GridView_VolunteersDirty.DataBind()
    End Sub

    Protected Sub GridView_VolunteersDirty_Sorting(sender As Object, e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles GridView_VolunteersDirty.Sorting
        Me.BindGV()
    End Sub
End Class

Partial Class WebForm_ManageWorkRecord_AddDirtyHeader

    Public Sub InitData(ByVal intFindDirtyHeaderID As Integer, ByVal intWorkHeaderID As Integer)

        FindDirtyHeaderID = intFindDirtyHeaderID
        WorkHeaderID = intWorkHeaderID

  
        Me.plButtonList.Visible = True
        Me.AddWorkHeaderControl1.ValidationGroup = ""

        If intFindDirtyHeaderID = 0 Then
            '新增
            Me.DataAccessMode = FormDataAccessMode.Insert
            Me.plCleanResult.Visible = False

            'AddWorkHeaderControl1.DataAccessMode = FormViewMode.Insert
            AddWorkHeaderControl1.InitData(0)

            AddWorkHeaderControl1.PlanID = FindDirtyHeaderID
            txtDirtyHeaderName.Text = String.Empty

            btnSearchDirtyHeader.Enabled = True

            AddLeader1.InitData(0)
            Me.btnApprove.Visible = False
        ElseIf WorkHeaderID = 0 Then
            '認養
            Me.DataAccessMode = FormDataAccessMode.Take
            Me.plCleanResult.Visible = False

            AddLeader1.InitData(WorkHeaderID)
            Me.lblTotal.Text = ""
            Me.BindFV()
            Me.BindGV()
            'AddWorkHeaderControl1.PlanID = Me.fv.DataKey("PlanID").ToString()
            Me.btnApprove.Visible = False
        Else
            '編輯
            'Me.DataAccessMode = FormDataAccessMode.Execute

            If Me.DataAccessMode = FormDataAccessMode.View Then
                Me.plButtonList.Visible = False
            End If

            Me.plCleanResult.Visible = True
            Me.AddWorkHeaderControl1.ValidationGroup = Me.ValidationGroup
            AddWorkHeaderControl1.DataAccessMode = FormDataAccessMode.Execute
            AddWorkHeaderControl1.InitData(WorkHeaderID)
            AddLeader1.InitData(WorkHeaderID)

            '繫結清潔內容的資料
            Me.AddWorkItemControl1.BindWorkItemForEdit(WorkHeaderID)

            Me.BindFV()

            AddWorkHeaderControl1.PlanID = Me.fv.DataKey("FindDirtyHeaderID").ToString()

            btnSearchDirtyHeader.Enabled = False

            Me.btnApprove.Visible = Me.CanAdmin
            Me.BindGV()
        End If

        UploadFileControl1.strType = WorkHeaderID


        txtDefaultWorkHour.Text = "0"
        txtDefaultWorkTimes.Text = "1"

        VolunteerQueryControl1.InitData()

    End Sub

    Public Sub BindFV()
        Dim sql As New MyStringBuilder
        Dim dat As New clsData

        '取得PlanName
        sql.Length = 0
        sql.AppendFormat("SELECT (C.RegionName+B.RegionName+A.Location) as FullLocation,A.* ")
        sql.AppendFormat("FROM FindDirtyHeader A ")
        sql.AppendFormat("LEFT JOIN Region B on A.VillageId=B.RegionID ")
        sql.AppendFormat("LEFT JOIN Region C on B.Parent=C.RegionID ")
        sql.AppendFormat("WHERE ")
        sql.AppendFormat("FindDirtyHeaderID={0} ", FindDirtyHeaderID)

        Dim dtResult As DataTable = dat.GetData(sql)

        If (dtResult IsNot Nothing AndAlso dtResult.Rows.Count > 0) Then
            txtDirtyHeaderName.Text = dtResult.Rows(0).Item("FullLocation").ToString()
            Me.BindDirtyHeader()
        End If
    End Sub

    Private Sub BindTownID()
        Dim ddl As DropDownList = TryCast(fv.FindControl("ddlTownID"), DropDownList)

        ddl.DataTextField = "RegionName"
        ddl.DataValueField = "RegionID"

        ddl.DataSource = MyObj.GetTownData("TPC")
        ddl.DataBind()

        ddl.Items.Insert(0, MyObj.GetDDLPleaseChooseItem())
    End Sub

    Private Sub BindVillageID()
        Dim ddl As DropDownList = TryCast(fv.FindControl("ddlVillageID"), DropDownList)

        ddl.DataTextField = "RegionName"
        ddl.DataValueField = "RegionID"
        ddl.DataSource = MyObj.GetVillageData(TryCast(fv.FindControl("ddlTownID"), DropDownList).SelectedValue)
        ddl.DataBind()
    End Sub

    Private Sub BindDirtyItemForInsert()
        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        sql.AppendFormat("select a.Value,a.Text, ")
        sql.AppendFormat("b.Value as SubValue,b.Text as SubText ")
        sql.AppendFormat("from CodeMapping a inner join CodeMapping b ")
        sql.AppendFormat("on a.TableName+'_'+a.ColumnName+'_'+a.Value = b.TableName ")
        sql.AppendFormat("where a.TableName = 'FindDirtyItem' and a.ColumnName='DirtyItemGroup' ")

        'AddHandler TryCast(Me.fv.FindControl("gvDirtyItem"), GridView).RowDataBound, AddressOf Me.gv_RowDataBound
        TryCast(Me.fv.FindControl("gvDirtyItem"), GridView).DataSource = dat.GetData(sql)
        TryCast(Me.fv.FindControl("gvDirtyItem"), GridView).DataBind()

    End Sub

    Private Sub BindDirtyItemForEdit(ByVal FindDirtyHeaderID As String)
        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        sql.AppendFormat("Select * from FindDirtyItem")
        sql.AppendFormat(" where FindDirtyHeaderID='{0}' ", FindDirtyHeaderID)

        Dim dt As Data.DataTable = dat.GetData(sql)

        Dim gvDirtyItem As GridView = TryCast(Me.fv.FindControl("gvDirtyItem"), GridView)


        Dim lblDirtyItemName As Label
        Dim cbList As CheckBoxList
        Dim lblValue As Label
        Dim lblSubValue As Label
        Dim txtNum As TextBox

        Dim ddlDirtyLevel As DropDownList

        For j As Integer = 0 To dt.Rows.Count - 1
            For i As Integer = 0 To gvDirtyItem.Rows.Count - 1
                lblDirtyItemName = TryCast(gvDirtyItem.Rows(i).FindControl("lblDirtyItemName"), Label)
                cbList = TryCast(gvDirtyItem.Rows(i).FindControl("cbList"), CheckBoxList)
                lblValue = TryCast(gvDirtyItem.Rows(i).FindControl("lblValue"), Label)
                lblSubValue = TryCast(gvDirtyItem.Rows(i).FindControl("lblSubValue"), Label)
                txtNum = TryCast(gvDirtyItem.Rows(i).FindControl("txtNum"), TextBox)

                ddlDirtyLevel = TryCast(gvDirtyItem.Rows(i).FindControl("ddlDirtyLevel"), DropDownList)


                If lblValue.Text = dt.Rows(j)("ItemGroupID").ToString() And lblSubValue.Text = dt.Rows(j)("ItemID").ToString() Then
                    cbList.Items(0).Selected = True
                    txtNum.Text = dt.Rows(j)("Amount").ToString()
                    ddlDirtyLevel.SelectedIndex = ddlDirtyLevel.Items.IndexOf(ddlDirtyLevel.Items.FindByValue(dt.Rows(j)("DirtyLevel").ToString()))
                    Exit For
                End If

            Next
        Next
    End Sub

    Private Sub BindDirtyLevel(ByVal ddl As DropDownList)
        ddl.DataTextField = "Text"
        ddl.DataValueField = "Value"
        ddl.DataSource = MyObj.GetCodeMappingData("FindDirtyItem", "DirtyLevel")
        ddl.DataBind()

        ddl.Items.Insert(0, MyObj.GetDDLPleaseChooseItem())
    End Sub

    Private Sub BindDirtyHeader()

        Me.fv.ChangeMode(FormViewMode.Edit)

        Dim sql As New MyStringBuilder
        Dim dat As New clsData

        sql.AppendFormat("select a.*,b.RegionID ")
        sql.AppendFormat(", PhotoFullPath = uf.FullPath ")
        sql.AppendFormat("from FindDirtyHeader a ")
        sql.AppendFormat(" join Region b on Left(a.VillageID,3)=b.RegionID ")
        sql.AppendFormat(" and b.RegionType='T'")
        sql.AppendFormat("left join UploadFileView uf on A.PhotoPathID = uf.FileSaveName ")
        sql.AppendFormat(" where a.FindDirtyHeaderID='{0}' ", FindDirtyHeaderID)

        Me.fv.DataSource = dat.GetData(sql)
        Me.fv.DataBind()

        Me.BindDirtyItemForEdit(FindDirtyHeaderID)
    End Sub

#Region "Property"

    Public Property DataAccessMode() As FormDataAccessMode
        Get
            Return ViewState("DataAccessMode")
        End Get
        Set(ByVal value As FormDataAccessMode)
            ViewState("DataAccessMode") = value
        End Set
    End Property

    Public Property FindDirtyHeaderID() As Integer
        Get
            Return ViewState("FindDirtyHeaderID")
        End Get
        Set(ByVal value As Integer)
            ViewState("FindDirtyHeaderID") = value
        End Set
    End Property

    Public Property WorkHeaderID() As Integer
        Get
            Return ViewState("WorkHeaderID")
        End Get
        Set(ByVal value As Integer)
            ViewState("WorkHeaderID") = value
        End Set
    End Property

    Public Property Approved() As Boolean
        Get
            If ViewState("Approved") Is Nothing Then
                ViewState("Approved") = False
            End If

            Return ViewState("Approved")
        End Get
        Set(ByVal value As Boolean)
            ViewState("Approved") = value
        End Set
    End Property

    Public ReadOnly Property FindDirtyPhotoWidth() As Integer
        Get
            If ViewState("FindDirtyPhotoWidth") Is Nothing Then
                ViewState("FindDirtyPhotoWidth") = MyObj.GetParameter("FindDirtyHeader", "PhotoWidth")
            End If

            Return ViewState("FindDirtyPhotoWidth")
        End Get
    End Property

    Public ReadOnly Property FindDirtyPhotoHeight() As Integer
        Get
            If ViewState("FindDirtyPhotoHeight") Is Nothing Then
                ViewState("FindDirtyPhotoHeight") = MyObj.GetParameter("FindDirtyHeader", "PhotoHeight")
            End If

            Return ViewState("FindDirtyPhotoHeight")
        End Get
    End Property

    Public ReadOnly Property ValidationGroup() As String
        Get
            Return "AddWorkHeaderB"
        End Get
    End Property

#End Region

    Public Enum FormDataAccessMode
        Insert
        Take
        Execute
        Approve
        View
    End Enum
End Class

